/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.stfalcon.sample.ability;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.Image;

import com.chinasoft_ohos.commontools.toast.Toast;
import com.stfalcon.imageviewer.StfalconImageViewer;
import com.stfalcon.sample.ResourceTable;
import com.stfalcon.sample.common.models.Demo;
import com.stfalcon.sample.common.models.Poster;
import com.stfalcon.sample.common.ui.views.PosterOverlayView;
import com.stfalcon.sample.dialog.StylingOptions;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.stfalcon.sample.dialog.StylingOptions.Property.HIDE_STATUS_BAR;
import static com.stfalcon.sample.dialog.StylingOptions.Property.IMAGES_MARGIN;
import static com.stfalcon.sample.dialog.StylingOptions.Property.RANDOM_BACKGROUND;
import static com.stfalcon.sample.dialog.StylingOptions.Property.SHOW_OVERLAY;
import static com.stfalcon.sample.dialog.StylingOptions.Property.SHOW_TRANSITION;
import static com.stfalcon.sample.dialog.StylingOptions.Property.SWIPE_TO_DISMISS;
import static com.stfalcon.sample.dialog.StylingOptions.Property.ZOOMING;

/**
 * StylingAbility
 *
 * @since 2021-07-23
 */
public class StylingAbility extends Ability {
    private static final int POS_0 = 0;
    private static final int POS_1 = 1;
    private static final int POS_2 = 2;
    private static final int POS_3 = 3;
    private static final int POS_4 = 4;
    private static final int POS_5 = 5;
    private static final int POS_6 = 6;
    private static final int POS_7 = 7;
    private static final int POS_8 = 8;
    private StfalconImageViewer<Integer> imageViewer;
    private final List<Image> horizontalImages = new ArrayList<>();
    private final List<Integer> horizontalResources = new ArrayList<>();
    private StylingOptions options = null;
    private PosterOverlayView overlayView = null;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_styling);
        options = StylingOptions.getInstance();
        initViews();
        initImage();
        findComponentById(ResourceTable.Id_setting).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                options.showDialog(getContext());
            }
        });
    }

    private void initImage() {
        horizontalResources.add(ResourceTable.Media_vincent);
        horizontalResources.add(ResourceTable.Media_jules);
        horizontalResources.add(ResourceTable.Media_korben);
        horizontalResources.add(ResourceTable.Media_toretto);
        horizontalResources.add(ResourceTable.Media_marty);
        horizontalResources.add(ResourceTable.Media_driver);
        horizontalResources.add(ResourceTable.Media_frank);
        horizontalResources.add(ResourceTable.Media_max);
        horizontalResources.add(ResourceTable.Media_daniel);
        for (Image image : horizontalImages) {
            image.setClickedListener(component -> {
                int startPosition;
                switch (component.getId()) {
                    case ResourceTable.Id_postersSecondImage:
                        startPosition = POS_1;
                        break;
                    case ResourceTable.Id_postersThirdImage:
                        startPosition = POS_2;
                        break;
                    case ResourceTable.Id_postersFourthImage:
                        startPosition = POS_3;
                        break;
                    case ResourceTable.Id_postersFifthImage:
                        startPosition = POS_4;
                        break;
                    case ResourceTable.Id_postersSixthImage:
                        startPosition = POS_5;
                        break;
                    case ResourceTable.Id_postersSeventhImage:
                        startPosition = POS_6;
                        break;
                    case ResourceTable.Id_postersEighthImage:
                        startPosition = POS_7;
                        break;
                    case ResourceTable.Id_postersNinthImage:
                        startPosition = POS_8;
                        break;
                    default:
                        startPosition = POS_0;
                        break;
                }
                showViewer(image, startPosition);
            });
        }
    }

    private void initViews() {
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersFirstImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersSecondImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersThirdImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersFourthImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersFifthImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersSixthImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersSeventhImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersEighthImage));
        horizontalImages.add((Image) findComponentById(ResourceTable.Id_postersNinthImage));
    }

    private void showViewer(Image image, int startPosition) {
        ArrayList<Poster> posters = new ArrayList<>(Demo.POSTERS);
        StfalconImageViewer.Builder<Integer> builder = new StfalconImageViewer.Builder<>(getContext(),
            horizontalResources, Image::setImageAndDecodeBounds)
            .withStartPosition(startPosition)
            .withImageChangeListener(position -> {
                if (imageViewer != null && options.isPropertyEnabled(SHOW_TRANSITION)) {
                    imageViewer.updateTransitionImage(horizontalImages.get(position));
                }
                if (overlayView != null) {
                    overlayView.update(posters.get(position));
                }
            })
            .withDismissListener(() -> Toast.show(getString(ResourceTable.String_message_on_dismiss)));
        builder.withHiddenStatusBar(options.isPropertyEnabled(HIDE_STATUS_BAR));
        if (options.isPropertyEnabled(IMAGES_MARGIN)) {
            final int margin = 48;
            builder.withImagesMargin(AttrHelper.vp2px(margin, getContext()));
        }
        if (options.isPropertyEnabled(SHOW_TRANSITION)) {
            builder.withTransitionFrom(image);
        }
        builder.allowSwipeToDismiss(options.isPropertyEnabled(SWIPE_TO_DISMISS));
        builder.allowZooming(options.isPropertyEnabled(ZOOMING));
        List<Integer> list = new ArrayList<>(horizontalResources);
        if (options.isPropertyEnabled(SHOW_OVERLAY)) {
            overlayView = new PosterOverlayView(getContext());
            overlayView.update(posters.get(startPosition));
            builder.withOverlayView(overlayView);
            overlayView.findComponentById(ResourceTable.Id_posterOverlayDeleteButton).setClickedListener(component -> {
                handleDeleted(posters, list);
            });
        }
        if (options.isPropertyEnabled(RANDOM_BACKGROUND)) {
            builder.withBackgroundColor(getRandomColor());
        }
        imageViewer = builder.show();
    }

    private void handleDeleted(ArrayList<Poster> posters, List<Integer> list) {
        if (imageViewer != null) {
            int currentPosition = imageViewer.currentPosition();
            if (list.size() > 0) {
                int position = currentPosition;
                if (currentPosition == list.size() - 1) {
                    position = currentPosition - 1;
                }
                list.remove(currentPosition);
                posters.remove(currentPosition);
                imageViewer.updateImages(list);
                if (position >= 0) {
                    overlayView.update(posters.get(position));
                }
            } else {
                imageViewer.close();
            }
        }
    }

    private int getRandomColor() {
        Random random = new Random();
        final int rgb = 156;
        final int alpha = 255;
        return new RgbColor(random.nextInt(rgb), random.nextInt(rgb), random.nextInt(rgb), alpha).asArgbInt();
    }
}
